package com.jieshuibao.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jieshuibao.common.config.Const;
import com.jieshuibao.common.config.enumtype.QuestionStatus;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.model.db.Answer;
import com.jieshuibao.model.db.AnswerUser;
import com.jieshuibao.model.db.Duty;
import com.jieshuibao.model.db.Question;
import com.jieshuibao.model.db.QuestionEx;
import com.jieshuibao.model.db.QuestionExample;
import com.jieshuibao.model.db.QuestionExample.Criteria;
import com.jieshuibao.model.db.QuestionUserAnswerRewardFlow;
import com.jieshuibao.model.db.QuestionUserEx;
import com.jieshuibao.model.db.QuestionUserExample;
import com.jieshuibao.model.db.QuestionUserKey;
import com.jieshuibao.model.db.QuestionUserOwnMsg;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.domain.AddAdmireRequest;
import com.jieshuibao.model.domain.AddAdmireResponse;
import com.jieshuibao.model.domain.AdmireQuestionResponse;
import com.jieshuibao.model.domain.AllAnswerResponse;
import com.jieshuibao.model.domain.AnswerAcceptResponse;
import com.jieshuibao.model.domain.CookieUser;
import com.jieshuibao.model.domain.PagePhone;
import com.jieshuibao.model.domain.QuestionAcceptAnswerRequest;
import com.jieshuibao.model.domain.QuestionAdmireRequest;
import com.jieshuibao.model.domain.QuestionAdmireResponse;
import com.jieshuibao.model.domain.QuestionRequest;
import com.jieshuibao.model.domain.QuestionResponse;
import com.jieshuibao.model.domain.SecretlyQuestionResponse;
import com.jieshuibao.model.domain.WxAppResponse;
import com.jieshuibao.service.AnswerService;
import com.jieshuibao.service.AnswerUserService;
import com.jieshuibao.service.CompanyService;
import com.jieshuibao.service.CounselorDutyService;
import com.jieshuibao.service.CounselorService;
import com.jieshuibao.service.DiscussUserService;
import com.jieshuibao.service.IntegralService;
import com.jieshuibao.service.LevelService;
import com.jieshuibao.service.PayVipBanlanceService;
import com.jieshuibao.service.PraiseService;
import com.jieshuibao.service.QuestionExService;
import com.jieshuibao.service.QuestionService;
import com.jieshuibao.service.QuestionUserService;
import com.jieshuibao.service.RedisService;
import com.jieshuibao.service.SensitivewordFilterService;
import com.jieshuibao.service.UserService;
import com.jieshuibao.service.WeiXinPayService;
import com.jieshuibao.service.WxOrderService;
import com.jieshuibao.util.Base64ForImg;
import com.jieshuibao.util.NetworkUtil;
import com.jieshuibao.util.PayTypeUtil;
import com.jieshuibao.util.StringUtils;
import com.jieshuibao.util.UUIDGenerator;
import com.jieshuibao.wx.po.WxAppPayReq;
import com.jieshuibao.wx.po.WxAppPayRes;
import com.jieshuibao.wx.po.WxJsPayReq;
import com.jieshuibao.wx.po.WxjsPayRes;
import com.jieshuibao.wx.util.PayCommonUtil;

@Controller
@RequestMapping(value = "/question")
public class QuestionController {
	private static final Logger logger = LoggerFactory
			.getLogger("QuestionController.class");

	private static final ObjectMapper mapper = new ObjectMapper();
	@Resource
	private UserService userService;
	
	@Resource
	private CounselorDutyService counselorDutyService;
	@Resource
	private CounselorService counselorService;
	@Resource
	private QuestionExService questionExService;
	@Resource
	private LevelService levelService;
	@Resource
	private RedisService redisService;
	@Resource
	private AnswerService answerService;
	@Resource
	private AnswerUserService answerUserService;
	@Resource
	private QuestionService questionService;
	@Resource
	private QuestionUserService questionUserService;

	@Resource
	private DiscussUserService discussUserService;

	@Resource
	private WeiXinPayService weiXinPayService;

	@Resource
	private WxOrderService wxOrderService;
	
	@Resource
	private CompanyService companyService;
	@Resource
	private PayVipBanlanceService payVipBanlanceService;
	
	@Resource
	private SensitivewordFilterService SensitivewordFilterService;
	
	@Resource
	private IntegralService IntegralService;
	
	@Resource
	private PraiseService praiseService;

	@Value("${question.images.path}")
	private String questionImagesPath;

	@Value("${images.basePath}")
	private String imagesBasePath;

	@Value("${question.images.url}")
	private String questionImagesUrl;

	@Value("${producttype.ttk}")
	private String producttypeTtk;
	@Value("${producttype.xs}")
	private String producttypeXs;
	
	@Value("${question.end.date}")
	private int questionEndDate;
	
	@Value("${min.money}")
	private int minMoney;
	
	@Value("${add.money}")
	private int addMoney; 
	
	@Value("${national.money}")
	private double nationalMoney;

	@RequestMapping(value = "/pageList", method = RequestMethod.POST)
	@ResponseBody
	public Object pageList(HttpServletRequest request,
			@RequestBody QuestionRequest questionRequest) {
		QuestionResponse questionResponse = new QuestionResponse();
		try {
			logger.info("接收：" + mapper.writeValueAsString(questionRequest));

			//String cookieId = request.getHeader("cookieId");
			//CookieUser cookieUser = redisService.getObejct(cookieId,
					//CookieUser.class);
			CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
			//if (null != cookieId) {
				if (cookieUser != null) {
					String phoneNumber = cookieUser.getPhoneNumber();
					if (null != phoneNumber) {
						User user = userService.getUserByPhoneNumber(phoneNumber);
						
						QuestionExample questionExample = new QuestionExample();

						questionExample.setOrderByClause("date desc");
						Criteria criteria = questionExample.createCriteria();
						Criteria criteria2 = questionExample.createCriteria();
						criteria.andPhoneNumNotEqualTo(phoneNumber);
						criteria.andStatusBetween(1, 2);
						//criteria.andAnswerNumBetween(0, 2);
						criteria.andAnswerNumLessThan(2);
						criteria2.andAnswerUserPhonesNotLike("%" + phoneNumber
								+ "%");
						criteria.andPayStatusEqualTo("0");
						criteria.andDelFlagEqualTo("0");
						int sinceId = questionRequest.getSinceId();
						int maxId = questionRequest.getMaxId();
						//String area = questionRequest.getArea();
						
						if (sinceId <= 0) {
							sinceId = 1;
						}
						if (maxId <= 0 || maxId < sinceId) {
							maxId = sinceId;
						}
						questionExample.setPageIndex(sinceId - 1);
						questionExample.setPageSize(maxId - sinceId + 1);
						
						
						PagePhone pagePhone = new PagePhone();
							
						pagePhone.setPageIndex(sinceId - 1);
						pagePhone.setPageSize(maxId - sinceId + 1);
						pagePhone.setPhoneNum(phoneNumber);
						if(user==null){
							questionResponse.setCode("2");
							questionResponse.setDes("请重新登录");
							return questionResponse;
						}else {
							pagePhone.setArea(user.getProvince());
						}
						/*List<QuestionEx> pageQuestions = questionExService
								.getPageQuestion(questionExample);*/
						List<QuestionEx> pageQuestionTwo = questionExService.getPageQuestionTwo(pagePhone);
						/**
						 * 抢答同一个人的问题一天之内超过三次移除
						 */
						for (int j = 0; j < pageQuestionTwo.size(); j++) {
							QuestionEx questionEx = pageQuestionTwo.get(j);
							String phoneNumber2 = questionEx.getPhoneNumber();
							String string = redisService.get(phoneNumber2+"_"+phoneNumber+"_CA");
							if(string!=null&&Integer.valueOf(string)>=3){
								pageQuestionTwo.remove(j);
							}
						}
						
						for (QuestionEx questionEx : pageQuestionTwo) {
							String counselorDuty = questionEx.getCounselorDuty();
							if(counselorDuty!=null&&!counselorDuty.equals("")){
								StringBuilder stringBuilder=new StringBuilder();
								String[] dutys = counselorDuty.split(",");
								if(dutys!=null){
									for (String id : dutys) {
										if(id!=null&&!id.equals("")){
											Duty duty = counselorDutyService.getDutyById(id);
											if(duty!=null){
												stringBuilder.append(duty.getDutyName()+" ");
											}
											
										}
										
									}
									int i = stringBuilder.lastIndexOf(" ");
									stringBuilder.delete(i, i+1);
									questionEx.setCounselorDuty(stringBuilder.toString());
								}
								
							}
						}
						questionResponse.setQuestions(pageQuestionTwo);
						questionResponse.setCode("1");
						questionResponse.setSinceId(sinceId);
						questionResponse.setMaxId(sinceId
								+ pageQuestionTwo.size() - 1);
						questionResponse.setCount(pageQuestionTwo.size());
						questionResponse
								.setQuestionImagesUrl(questionImagesUrl);
					} else {
						questionResponse.setCode("2");
						questionResponse.setDes("请重新登录");
					}
				} else {
					questionResponse.setCode("2");
					questionResponse.setDes("请重新登录");

				}

			//} else {
				//questionResponse.setCode("2");
				//questionResponse.setDes("请重新登录");

			//}
			logger.info("返回：" + mapper.writeValueAsString(questionResponse));
		} catch (Exception e) {
			questionResponse.setCode("0");
			questionResponse.setDes("系统繁忙");
			e.printStackTrace();

		}

		return questionResponse;
	}

	// 我问的悬赏问题列表
	@RequestMapping(value = "/admireList", method = RequestMethod.POST)
	@ResponseBody
	public Object queryAllAdmireQuestion(HttpServletRequest request,
			@RequestBody QuestionRequest questionRequest) {
		AdmireQuestionResponse questionResponse = new AdmireQuestionResponse();
		try {
			logger.info("接收：" + mapper.writeValueAsString(questionRequest));

			CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
				// String phoneNumber = redisService.get(cookieId);
				if (cookieUser != null) {
					String phoneNumber = cookieUser.getPhoneNumber();
					if (null != phoneNumber) {
						QuestionExample questionExample = new QuestionExample();
						int sinceId = questionRequest.getSinceId();
						int maxId = questionRequest.getMaxId();

						if (sinceId <= 0) {
							sinceId = 1;
						}
						if (maxId <= 0 || maxId < sinceId) {
							maxId = sinceId;
						}
						questionExample.setOrderByClause("date desc");
						questionExample.setPageIndex(sinceId - 1);
						questionExample.setPageSize(maxId - sinceId + 1);
						Criteria criteria = questionExample.createCriteria();
						criteria.andPhoneNumEqualTo(phoneNumber);
						criteria.andDelFlagEqualTo("0");
						criteria.andPayStatusEqualTo("0");
						List<QuestionEx> questions = questionExService
								.getPageQuestion(questionExample);
						for (QuestionEx questionEx : questions) {
							QuestionUserExample questionUserExample2 = new QuestionUserExample();
							String counselorDuty = questionEx.getCounselorDuty();
							if(counselorDuty!=null&&!counselorDuty.equals("")){
								StringBuilder stringBuilder=new StringBuilder();
								String[] dutys = counselorDuty.split(",");
								if(dutys!=null){
									for (String id : dutys) {
										if(id!=null&&!id.equals("")){
											Duty duty = counselorDutyService.getDutyById(id);
											if(duty!=null){
												stringBuilder.append(duty.getDutyName()+" ");
											}
											
										}
										
									}
									int i = stringBuilder.lastIndexOf(" ");
									stringBuilder.delete(i, i+1);
									questionEx.setCounselorDuty(stringBuilder.toString());
								}
								
							}
							com.jieshuibao.model.db.QuestionUserExample.Criteria createCriteria = questionUserExample2.createCriteria();
							createCriteria.andQuestionUuidEqualTo(questionEx.getUuid());
							int lookNum = questionUserService
									.countUser(questionUserExample2);
							questionEx.setLookNum(lookNum);
							
						}
						
						
						questionResponse.setCode("1");// 成功
						questionResponse.setQuestions(questions);
						questionResponse.setSinceId(sinceId);
						questionResponse.setMaxId(sinceId + questions.size()
								- 1);
						questionResponse.setRows(questions.size());
						questionResponse
								.setQuestionImagesUrl(questionImagesUrl);
					} else {
						questionResponse.setCode("2");
						questionResponse.setDes("请重新登录");
					}
				} else {
					questionResponse.setCode("2");
					questionResponse.setDes("请重新登录");
				}

			logger.info("返回：" + mapper.writeValueAsString(questionResponse));

		} catch (Exception e) {
			e.printStackTrace();
			questionResponse.setCode("0");
			questionResponse.setDes("系统繁忙请稍后再试！");
		}

		return questionResponse;

	}
	
	
	
	// 我回答的悬赏问题列表
	@RequestMapping(value = "/answerQuestionList", method = RequestMethod.POST)
	@ResponseBody
	public Object queryAdmireQuestion(HttpServletRequest request,
			@RequestBody QuestionRequest questionRequest) {
		AdmireQuestionResponse questionResponse = new AdmireQuestionResponse();
		try {
			logger.info("接收：" + mapper.writeValueAsString(questionRequest));

	
				CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
				if(cookieUser!=null){
					
					String phoneNumber = cookieUser.getPhoneNumber();
					if (null != phoneNumber) {
						//QuestionExample questionExample = new QuestionExample();
						int sinceId = questionRequest.getSinceId();
						int maxId = questionRequest.getMaxId();

						if (sinceId <= 0) {
							sinceId = 1;
						}
						if (maxId <= 0 || maxId < sinceId) {
							maxId = sinceId;
						}
						PagePhone pagePhone = new PagePhone();

						pagePhone.setPageIndex(sinceId - 1);
						pagePhone.setPageSize(maxId - sinceId + 1);
						pagePhone.setPhoneNum(phoneNumber);
						List<QuestionUserAnswerRewardFlow> questionUserAnswerRewardFlow = questionExService.getQuestionUserAnswerRewardFlow(pagePhone);
						
						for (QuestionUserAnswerRewardFlow questionEx : questionUserAnswerRewardFlow) {
							QuestionUserExample questionUserExample2 = new QuestionUserExample();
							String counselorDuty = questionEx.getCounselorDuty();
							if(counselorDuty!=null&&!counselorDuty.equals("")){
								StringBuilder stringBuilder=new StringBuilder();
								String[] dutys = counselorDuty.split(",");
								if(dutys!=null){
									for (String id : dutys) {
										if(id!=null&&!id.equals("")){
											Duty duty = counselorDutyService.getDutyById(id);
											if(duty!=null){
												stringBuilder.append(duty.getDutyName()+" ");
											}
											
										}
										
									}
									int i = stringBuilder.lastIndexOf(" ");
									stringBuilder.delete(i, i+1);
									questionEx.setCounselorDuty(stringBuilder.toString());
								}
								
							}
							
							
							Answer answer = answerUserService.getAnswerStatus(
									questionEx.getUuid(), phoneNumber);
							if (answer != null) {

								questionEx.setStatus(answer.getStatus());

							}
							com.jieshuibao.model.db.QuestionUserExample.Criteria createCriteria = questionUserExample2.createCriteria();
							createCriteria.andQuestionUuidEqualTo(questionEx.getUuid());
							int lookNum = questionUserService
									.countUser(questionUserExample2);
							questionEx.setLookNum(lookNum);
							
						}

						questionResponse.setCode("1");// 成功
						//questionResponse.setQuestions(questions);
						questionResponse.setQuestionUserAnswerRewardFlows(questionUserAnswerRewardFlow);
						questionResponse.setSinceId(sinceId);
						questionResponse.setMaxId(sinceId + questionUserAnswerRewardFlow.size() - 1);
						questionResponse.setRows(questionUserAnswerRewardFlow.size());
						questionResponse.setQuestionImagesUrl(questionImagesUrl);

					} else {
						questionResponse.setCode("2");
						questionResponse.setDes("请重新登录");
					}
				
				}else {
					questionResponse.setCode("2");
					questionResponse.setDes("请重新登录");
				}
			//} else {
				//questionResponse.setCode("2");
				//questionResponse.setDes("请重新登录");

			//}
			logger.info("返回：" + mapper.writeValueAsString(questionResponse));

		} catch (Exception e) {
			e.printStackTrace();
			questionResponse.setCode("0");
			questionResponse.setDes("系统繁忙请稍后再试！");
		}

		return questionResponse;

	}

	// 我提问的问题的详情
	@RequestMapping(value = "/acceptAnswer", method = RequestMethod.POST)
	@ResponseBody
	public Object admireQuestionDetail(HttpServletRequest request,
			@RequestBody QuestionAcceptAnswerRequest questionAcceptAnswerRequest) {
		AllAnswerResponse allAnswerResponse = new AllAnswerResponse();
		try {
			logger.info("接收："
					+ mapper.writeValueAsString(questionAcceptAnswerRequest));

				CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {
						//AnswerExample answerExample = new AnswerExample();
						int sinceId = questionAcceptAnswerRequest.getSinceId();
						int maxId = questionAcceptAnswerRequest.getMaxId();
						String questionUuid = questionAcceptAnswerRequest
								.getQuestionUuid();

						if (sinceId <= 0) {
							sinceId = 1;
						}
						if (maxId <= 0 || maxId < sinceId) {
							maxId = sinceId;
						}
						QuestionUserEx questionExByUuid = questionExService.getQuestionExByUuid(questionUuid);
						if (questionExByUuid==null) {
							allAnswerResponse.setCode(BaseRes.ERRORPARAM_CODE);
							allAnswerResponse.setDes(BaseRes.ERRORPARAM_DES);
							return allAnswerResponse;
						}
						String phoneNumber = questionExByUuid.getPhoneNumber();
						
						if (!phoneNumber.equals(phoneNum)) {
							allAnswerResponse.setCode(BaseRes.ERRORPARAM_CODE);
							allAnswerResponse.setDes(BaseRes.ERRORPARAM_DES);
							return allAnswerResponse;
						}
						allAnswerResponse.setQuestion(questionExByUuid);
						int status = questionExByUuid.getStatus();
						
						if (status== 1||status==2||status==5||status==6||status==7||status==8) {
							// 未被采纳答案的问题 跳转到答案选择页面
							PagePhone pagePhone = new PagePhone();

							pagePhone.setPageIndex(sinceId - 1);
							pagePhone.setPageSize(maxId - sinceId + 1);
							pagePhone.setPhoneNum(questionUuid);
							List<AnswerUser> answerUsers = answerUserService
									.getAnswerUsersByQuestionUuid(pagePhone);
							
							for (AnswerUser answerUser : answerUsers) {
								String counselorDuty = answerUser.getCounselorDuty();
								if(counselorDuty!=null&&!counselorDuty.equals("")){
									StringBuilder stringBuilder=new StringBuilder();
									String[] dutys = counselorDuty.split(",");
									if(dutys!=null){
										for (String id : dutys) {
											if(id!=null&&!id.equals("")){
												Duty duty = counselorDutyService.getDutyById(id);
												if(duty!=null){
													stringBuilder.append(duty.getDutyName()+" ");
												}
												
											}
											
										}
										int i = stringBuilder.lastIndexOf(" ");
										stringBuilder.delete(i, i+1);
										answerUser.setCounselorDuty(stringBuilder.toString());
									}
									
								}
								
							}
							allAnswerResponse.setCode("1");// 成功
							allAnswerResponse.setAnswerUsers(answerUsers);
							allAnswerResponse.setSinceId(sinceId);
							allAnswerResponse.setMaxId(sinceId
									+ answerUsers.size() - 1);
							allAnswerResponse.setRows(answerUsers.size());
						} else if (status == 3
								|| status == 4) {
							List<AnswerUser> answerUsers = answerUserService
									.getAnswerUserByQUid(questionUuid);
							for (AnswerUser answerUser : answerUsers) {
								String counselorDuty = answerUser.getCounselorDuty();
								if(StringUtils.isNotBlank(counselorDuty)){
									String dutyName = counselorDutyService.getCounselorDutyName(counselorDuty);
									answerUser.setCounselorDuty(dutyName);
									}
								
							}
							allAnswerResponse.setAnswerUsers(answerUsers);
							allAnswerResponse.setCode("1");

						} else {
							// 问题状态传输错误造成 系统繁忙
							// 状态错误
							allAnswerResponse.setCode("3");
							allAnswerResponse.setDes("状态错误！");
						}
					} else {
						// 重新登录
						allAnswerResponse.setCode("2");
						allAnswerResponse.setDes("重新登录");
					}
				} else {
					allAnswerResponse.setCode("2");
					allAnswerResponse.setDes("重新登录");
				}

			logger.info("返回：" + mapper.writeValueAsString(allAnswerResponse));

		} catch (Exception e) {

			e.printStackTrace();
			allAnswerResponse.setCode("0");
			allAnswerResponse.setDes("系统繁忙请稍后再试！");
		}
		return allAnswerResponse;
	}
	
	// 我提问的问题的详情 (添加提问本人的用户信息)
		@RequestMapping(value = "/acceptAnswerDetail", method = RequestMethod.POST)
		@ResponseBody
		public Object admireQuestionDetailMsg(HttpServletRequest request,
				@RequestBody QuestionAcceptAnswerRequest questionAcceptAnswerRequest) {
			AllAnswerResponse allAnswerResponse = new AllAnswerResponse();
			try {
				logger.info("接收："
						+ mapper.writeValueAsString(questionAcceptAnswerRequest));

					CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
					if (cookieUser != null) {
						String phoneNum = cookieUser.getPhoneNumber();
						if (phoneNum != null) {
							//AnswerExample answerExample = new AnswerExample();
							int sinceId = questionAcceptAnswerRequest.getSinceId();
							int maxId = questionAcceptAnswerRequest.getMaxId();
							String questionUuid = questionAcceptAnswerRequest
									.getQuestionUuid();

							if (sinceId <= 0) {
								sinceId = 1;
							}
							if (maxId <= 0 || maxId < sinceId) {
								maxId = sinceId;
							}
							int status = questionAcceptAnswerRequest.getStatus();
							
							if (status== 1||status==2||status==5||status==6) {
								// 未被采纳答案的问题 跳转到答案选择页面
								PagePhone pagePhone = new PagePhone();

								pagePhone.setPageIndex(sinceId - 1);
								pagePhone.setPageSize(maxId - sinceId + 1);
								pagePhone.setPhoneNum(questionUuid);
								List<AnswerUser> answerUsers = answerUserService
										.getAnswerUsersByQuestionUuid(pagePhone);
								
								for (AnswerUser answerUser : answerUsers) {
									String counselorDuty = answerUser.getCounselorDuty();
									if(counselorDuty!=null&&!counselorDuty.equals("")){
										StringBuilder stringBuilder=new StringBuilder();
										String[] dutys = counselorDuty.split(",");
										if(dutys!=null){
											for (String id : dutys) {
												if(id!=null&&!id.equals("")){
													Duty duty = counselorDutyService.getDutyById(id);
													if(duty!=null){
														stringBuilder.append(duty.getDutyName()+" ");
													}
													
												}
												
											}
											int i = stringBuilder.lastIndexOf(" ");
											stringBuilder.delete(i, i+1);
											answerUser.setCounselorDuty(stringBuilder.toString());
										}
										
									}
									
								}
								
								QuestionUserOwnMsg userMsgByPhoneNum = userService.getUserMsgByPhoneNum(phoneNum);
								//用户职责名称
								if(null!=userMsgByPhoneNum.getCounselorDuty()){
									String dutyName = counselorDutyService.getCounselorDutyName(userMsgByPhoneNum.getCounselorDuty());
									userMsgByPhoneNum.setCounselorDuty(dutyName);
								}
								//用户积分
								userMsgByPhoneNum.setIntegralScore(IntegralService.getIntegralScoreByUuid(phoneNum));
								allAnswerResponse.setQuestionUserOwnMsg(userMsgByPhoneNum);
								
								//String uuid 问题id //String content问题内容 //  Date date问题发布的时间   //String[] images问题图片
								QuestionUserEx questionExByUuid = questionExService.getQuestionExByUuid(questionUuid);
								userMsgByPhoneNum.setUuid(questionUuid);
								userMsgByPhoneNum.setContent(questionExByUuid.getContent()); 
								userMsgByPhoneNum.setDate(questionExByUuid.getDate());
								userMsgByPhoneNum.setImages(questionExByUuid.getImages());
								
								
								allAnswerResponse.setCode("1");// 成功
								allAnswerResponse.setAnswerUsers(answerUsers);
								allAnswerResponse.setSinceId(sinceId);
								allAnswerResponse.setMaxId(sinceId
										+ answerUsers.size() - 1);
								allAnswerResponse.setRows(answerUsers.size());
							} else if (questionAcceptAnswerRequest.getStatus() == 3
									|| questionAcceptAnswerRequest.getStatus() == 4) {
								List<AnswerUser> answerUsers = answerUserService
										.getAnswerUserByQUid(questionUuid);
								for (AnswerUser answerUser : answerUsers) {
									String counselorDuty = answerUser.getCounselorDuty();
									if(StringUtils.isNotBlank(counselorDuty)){
										String dutyName = counselorDutyService.getCounselorDutyName(counselorDuty);
										answerUser.setCounselorDuty(dutyName);
										}
									
								}
								allAnswerResponse.setAnswerUsers(answerUsers);
								allAnswerResponse.setCode("1");

							} else {
								// 问题状态传输错误造成 系统繁忙
								// 状态错误
								allAnswerResponse.setCode("3");
								allAnswerResponse.setDes("状态错误！");
							}
						} else {
							// 重新登录
							allAnswerResponse.setCode("2");
							allAnswerResponse.setDes("重新登录");
						}
					} else {
						allAnswerResponse.setCode("2");
						allAnswerResponse.setDes("重新登录");
					}

				logger.info("返回：" + mapper.writeValueAsString(allAnswerResponse));

			} catch (Exception e) {

				e.printStackTrace();
				allAnswerResponse.setCode("0");
				allAnswerResponse.setDes("系统繁忙请稍后再试！");
			}
			return allAnswerResponse;
		}
		
		// 我回答的别人问题的详情(添加提问问题的 用户的信息)

		@RequestMapping(value = "/otherQuestionDetail", method = RequestMethod.POST)
		@ResponseBody
		public Object admireAcceptAnswerDetail(HttpServletRequest request,
				@RequestBody QuestionAcceptAnswerRequest questionAcceptAnswerRequest) {
			AnswerAcceptResponse acceptResponse = new AnswerAcceptResponse();
			try {
				logger.info("接收："
						+ mapper.writeValueAsString(questionAcceptAnswerRequest));

					CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
					if (cookieUser != null) {
						String phoneNum = cookieUser.getPhoneNumber();
						System.out.println("回答问题手机号："+phoneNum);
						if (phoneNum != null) {
							// AnswerExample answerExample = new AnswerExample();
							String questionUuid = questionAcceptAnswerRequest
									.getQuestionUuid();
							if (questionUuid != null) {
								List<AnswerUser> answerUsers = answerUserService
										.getAnswerUserByPhoneAndQUuid(phoneNum,
												questionUuid);
								for (AnswerUser answerUser : answerUsers) {
									String counselorDuty = answerUser.getCounselorDuty();
									if(counselorDuty!=null&&!counselorDuty.equals("")){
										String dutyName = counselorDutyService.getCounselorDutyName(counselorDuty);
										answerUser.setCounselorDuty(dutyName);
										QuestionUserEx questionEx = questionExService.getQuestionExByUuid(questionUuid);
										if(null != questionEx){
											answerUser.setLookNum(questionEx.getLookNum());
										}
									}
									
								}
								
								//String uuid 问题id //String content问题内容 //  Date date问题发布的时间   //String[] images问题图片
								QuestionUserEx questionExByUuid = questionExService.getQuestionExByUuid(questionUuid);
								if(null != questionExByUuid){
									
									String questionPhoneNum = questionExService.getphoneNumByQuestionID(questionUuid);
									//添加问题id 对应的用户信息
									QuestionUserOwnMsg userMsgByPhoneNum = userService.getUserMsgByPhoneNum(questionPhoneNum);
									//用户职责名称
									if(null!=userMsgByPhoneNum){
										String dutyName = counselorDutyService.getCounselorDutyName(userMsgByPhoneNum.getCounselorDuty());
										userMsgByPhoneNum.setCounselorDuty(dutyName);
										//用户积分
										userMsgByPhoneNum.setIntegralScore(IntegralService.getIntegralScoreByUuid(phoneNum));
										acceptResponse.setQuestionUserOwnMsg(userMsgByPhoneNum);
										System.out.println("问题手机号："+questionPhoneNum);
										userMsgByPhoneNum.setPhoneNumber(questionPhoneNum);
										userMsgByPhoneNum.setUuid(questionUuid);
										userMsgByPhoneNum.setContent(questionExByUuid.getContent()); 
										userMsgByPhoneNum.setDate(questionExByUuid.getDate());
										userMsgByPhoneNum.setImages(questionExByUuid.getImages());
									}
									
								}
								
								
								
								acceptResponse.setAnswerUsers(answerUsers);
								acceptResponse.setCode("1");
							} else {
								// 数据格式错误
								acceptResponse.setCode("3");
								acceptResponse.setDes("数据格式错误");
							}

						} else {
							// 重新登录
							acceptResponse.setCode("2");
							acceptResponse.setDes("请重新登录");
						}
					} else {
						// 重新登录
						acceptResponse.setCode("2");
						acceptResponse.setDes("请重新登录");
					}

				logger.info("返回：" + mapper.writeValueAsString(acceptResponse));

			} catch (Exception e) {

				e.printStackTrace();
				acceptResponse.setCode("0");
				acceptResponse.setDes("系统繁忙请稍后再试！");
			}
			return acceptResponse;
		}
	
	// 我回答的别人问题的详情

	@RequestMapping(value = "/otherQuestion", method = RequestMethod.POST)
	@ResponseBody
	public Object admireAcceptAnswer(HttpServletRequest request,
			@RequestBody QuestionAcceptAnswerRequest questionAcceptAnswerRequest) {
		AnswerAcceptResponse acceptResponse = new AnswerAcceptResponse();
		try {
			logger.info("接收："
					+ mapper.writeValueAsString(questionAcceptAnswerRequest));

				CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {
						// AnswerExample answerExample = new AnswerExample();
						String questionUuid = questionAcceptAnswerRequest
								.getQuestionUuid();
						if (questionUuid != null) {
							List<AnswerUser> answerUsers = answerUserService
									.getAnswerUserByPhoneAndQUuid(phoneNum,
											questionUuid);
							for (AnswerUser answerUser : answerUsers) {
								String counselorDuty = answerUser.getCounselorDuty();
								if(counselorDuty!=null&&!counselorDuty.equals("")){
									String dutyName = counselorDutyService.getCounselorDutyName(counselorDuty);
									answerUser.setCounselorDuty(dutyName);
								}
								
							}
							int sinceId = questionAcceptAnswerRequest.getSinceId();
							int maxId = questionAcceptAnswerRequest.getMaxId();

							if (sinceId <= 0) {
								sinceId = 1;
							}
							if (maxId <= 0 || maxId < sinceId) {
								maxId = sinceId;
							}
							QuestionExample questionExample = new QuestionExample();
							questionExample.setPageIndex(sinceId - 1);
							questionExample.setPageSize(maxId - sinceId + 1);
							Criteria criteria = questionExample.createCriteria();
							criteria.andDelFlagEqualTo("0");
							criteria.andPayStatusEqualTo("0");
							criteria.andUuidEqualTo(questionUuid);
							List<QuestionEx> questions = questionExService
									.getPageQuestion(questionExample);
							if(questions != null && questions.size() == 1){
								acceptResponse.setQuestion(questions.get(0));
							}
							acceptResponse.setAnswerUsers(answerUsers);
							acceptResponse.setCode("1");
						} else {
							// 数据格式错误
							acceptResponse.setCode("3");
							acceptResponse.setDes("数据格式错误");
						}

					} else {
						// 重新登录
						acceptResponse.setCode("2");
						acceptResponse.setDes("请重新登录");
					}
				} else {
					// 重新登录
					acceptResponse.setCode("2");
					acceptResponse.setDes("请重新登录");
				}

			logger.info("返回：" + mapper.writeValueAsString(acceptResponse));

		} catch (Exception e) {

			e.printStackTrace();
			acceptResponse.setCode("0");
			acceptResponse.setDes("系统繁忙请稍后再试！");
		}
		return acceptResponse;
	}

	
	  // 加赏
	  
	@RequestMapping(value = "/addAdmire", method = RequestMethod.POST)
	@ResponseBody
	public Object addAdmire(HttpServletRequest request,

	@RequestBody AddAdmireRequest addAdmireRequest) {
		AddAdmireResponse addAdmireResponse = new AddAdmireResponse();
		WxAppResponse wxAppResponse = new WxAppResponse();
		try {
			//String cookieId = request.getHeader("cookieId");
			//if (cookieId != null) {
				//CookieUser cookieUser = redisService.getObejct(cookieId,
						//CookieUser.class);
				CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					int money = addAdmireRequest.getMoney();
					String questionUuid = addAdmireRequest.getQuestionUuid();
					String payType = addAdmireRequest.getPayType();
					Question question = questionService
							.getQuestionByUuid(questionUuid);
					if(money<addMoney){
						addAdmireResponse.setCode("3");
						addAdmireResponse.setDes("金额不能低于"+addMoney+"元");
						return addAdmireResponse;
					}
					if(question==null){
						addAdmireResponse.setCode("3");
						addAdmireResponse.setDes("没有找到此问题");
						return addAdmireResponse;
					}
					
					Integer answerNum = question.getAnswerNum();
					if(answerNum<3){
						addAdmireResponse.setCode("3");
						addAdmireResponse.setDes("此问题不符合加赏条件");
						return addAdmireResponse;
					}
					

					User user = userService.getUserByPhoneNumber(phoneNum);
					if(user==null){
						addAdmireResponse.setCode("2");
						addAdmireResponse.setDes("重新登录");
						return addAdmireResponse;
					}

					if (question.getRewardNum()==0) {
						Date endDate = question.getEndDate();
						Date date = new Date();
						if(date.after(endDate)){
							addAdmireResponse.setCode("3");
							addAdmireResponse.setDes("此问题已经到期");
							return addAdmireResponse;
						}
						
						if(payType.equals("balance")){
							HashMap<String,String> map = questionService.updateUserAndQuestionAndOrCompany(user, phoneNum, money, questionUuid, payType);
							return map;
							
						}else if(payType.equals("personal")){
							addAdmireResponse.setCode("3");
							addAdmireResponse.setDes("请更新版本");
							return addAdmireResponse;
							/*HashMap<String,String> map = questionService.updateUserAndQuestionAndOrCompany(user, phoneNum, money, questionUuid, payType);
							return map;	*/
						}else if(payType.equals("business")){//business
							addAdmireResponse.setCode("3");
							addAdmireResponse.setDes("请更新版本");
							return addAdmireResponse;
							/*HashMap<String,String> map = questionService.updateUserAndQuestionAndOrCompany(user, phoneNum, money, questionUuid, payType);
							return map;*/
						}else if(payType.equals("weixin")){
							WxAppPayReq wxAppPayReq = new WxAppPayReq();
							wxAppPayReq.setPhone(phoneNum);
							wxAppPayReq.setUnitPrice((double)money);
							wxAppPayReq.setProductName("加赏问题");
							wxAppPayReq.setProductType(Const.ADDXS);
							wxAppPayReq.setProductId(questionUuid);
							WxAppPayRes appPay = (WxAppPayRes) weiXinPayService
									.appPay(wxAppPayReq, request);
							BeanUtils.copyProperties(wxAppResponse,
									appPay);
							//wxAppResponse.setTime(date.getTime());
							return wxAppResponse;
						}else {
							addAdmireResponse.setCode("3");
							addAdmireResponse.setDes("请选择支付方式");
						}
						
						
					} else { // 加赏次数已使用完
						addAdmireResponse.setCode("4");
						addAdmireResponse.setDes("加赏次数已使用完");

					}
				

				} else { // 重新登录 addAdmireResponse.setCode("2");
					addAdmireResponse.setDes("请重新登录");
				}

			//} else { // 重新登录 addAdmireResponse.setCode("2");
				//addAdmireResponse.setDes("请重新登录");
			//}
		} catch (Exception e) { 
			addAdmireResponse.setCode("0");
			addAdmireResponse.setDes("系统繁忙请稍后再试！");
		}

		return addAdmireResponse;

	}
	 

	// 悬赏提交接口
	@RequestMapping(value = "/admireQuestion", method = RequestMethod.POST)
	@ResponseBody
	public Object admireQuestion(HttpServletRequest request,
			@RequestBody QuestionAdmireRequest questionAdmireRequest) {
		QuestionAdmireResponse questionAdmireResponse = new QuestionAdmireResponse();
		//WxAppResponse wxAppResponse = new WxAppResponse();
		try {
			logger.debug("接收：" + mapper.writeValueAsString(questionAdmireRequest));
			//String cookieId = request.getHeader("cookieId");
			//if (cookieId != null) {
				// String phoneNum = redisService.get(cookieId);
				//CookieUser cookieUser = redisService.getObejct(cookieId,
						//CookieUser.class);
				CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {
						String payType = questionAdmireRequest.getPayType();
						String content = questionAdmireRequest.getContent();
						//String orderNo = questionAdmireRequest.getOrderNo();
						//int money = questionAdmireRequest.getMoney();
						//String code = questionAdmireRequest.getCode();
						//int source = questionAdmireRequest.getSource();
						//String area = questionAdmireRequest.getArea();
						String trade = questionAdmireRequest.getTrade();
						String isAnon = questionAdmireRequest.getIsAnon();
						
						String ipAddress = NetworkUtil.getIpAddress(request);
						
						Question question = new Question();
						question.setQuIp(ipAddress);
						
					
						User user = userService
								.getUserByPhoneNumber(phoneNum);
						if (user== null) {
							questionAdmireResponse.setCode("2");
							questionAdmireResponse.setDes("重新登录!");
							return questionAdmireResponse;
						}
					
						/*if(money<minMoney){
							questionAdmireResponse.setCode("3");
							questionAdmireResponse
									.setDes("悬赏金额不能低于"+minMoney+"元");
							return questionAdmireResponse;
						}*/
						
					
						if (StringUtils.isBlank(trade)) {
							question.setTrade(user.getTrade());
						}else {
							question.setTrade(trade);
						}
						
						
						/*if(area==null||area.equals("")||area.equals("全国")){
							if(money<nationalMoney){
								questionAdmireResponse.setCode("3");
								questionAdmireResponse
										.setDes("悬赏金额不能低于"+nationalMoney+"元");
								return questionAdmireResponse;
							}
							question.setArea("全国");
						}else{
							String province = user.getProvince();
							if(!area.equals(province)){
								questionAdmireResponse.setCode("3");
								questionAdmireResponse.setDes("您选择发布的区域与您资料中的区域不相同，请重新选择");
								return questionAdmireResponse;
							}
							if(money<minMoney){
								questionAdmireResponse.setCode("3");
								questionAdmireResponse
								.setDes("悬赏金额不能低于"+minMoney+"元");
								return questionAdmireResponse;
							}
							question.setArea(area);
						}*/
						String province = user.getProvince();
					/*	if (StringUtils.isBlank(area)) {
							questionAdmireResponse.setCode("3");
							questionAdmireResponse
									.setDes("地区不能为空");
							return questionAdmireResponse;
						}*/
						String address = user.getAddress();
						
							question.setArea(province+" "+address);
						if (StringUtils.isNotBlank(payType)) {
							questionAdmireResponse.setCode("3");
							questionAdmireResponse
									.setDes("请更新版本");
							return questionAdmireResponse;
							
						}
						if (content != null && !content.equals("")) {
						
								String uuid = UUIDGenerator.getUUID();
								
								question.setContent(content);
								//SensitivewordFilter sensitivewordFilter = new SensitivewordFilter();
								//boolean containtSensitiveWord = sensitivewordFilter.isContaintSensitiveWord(content, 2);
								boolean containtSensitiveWord = SensitivewordFilterService.isContaintSensitiveWord(content, 2);
								if (containtSensitiveWord) {
									questionAdmireResponse.setCode("3");
									questionAdmireResponse
											.setDes("包含非法词请检查后输入");
									return questionAdmireResponse;
									
								}
								boolean adopQuestion = questionService.isAdopQuestion(phoneNum);
							
								BaseRes<String> res = questionService.IntegralUserQuestion(phoneNum);
								if (!res.getCode().equals(BaseRes.SUCCESS_CODE)) {
									return res;
								}
							
								boolean completeUser = userService.isCompleteUser(phoneNum);
								if (!completeUser) {
									questionAdmireResponse.setCode(BaseRes.ERRORPARAM_CODE);
									questionAdmireResponse.setDes("请完善用户信息");
									return questionAdmireResponse;
								}
								if (adopQuestion) {
									questionAdmireResponse.setCode(BaseRes.ERRORPARAM_CODE);
									questionAdmireResponse.setDes("您还有问题尚未采纳，请采纳后再进行发布！");
									return questionAdmireResponse;
								}
								if (StringUtils.isBlank(isAnon)) {
									questionAdmireResponse.setCode(BaseRes.ERRORPARAM_CODE);
									questionAdmireResponse.setDes(BaseRes.ERRORPARAM_DES);
									return questionAdmireResponse;
								}else if (isAnon.equals("0")) {
									question.setIsAnon("0");
								}else{
									question.setIsAnon("1");
								}
								// 设置提问时间以及结束时间
								Date date = new Date();
								
								question.setDate(date);
								Calendar calendar = Calendar.getInstance();
								calendar.setTimeInMillis((date.getTime())
										+ ((long) questionEndDate) * 24 * 3600 * 1000);
								question.setEndDate(calendar.getTime());
								question.setMoney(minMoney);
								question.setPhoneNum(phoneNum);
								
								List<String> images = questionAdmireRequest.getImages();
										
								// 图片处理
								if (images != null && images.size() > 0) {
									int i = 1;

									List<String> imgs = new ArrayList<String>();

									for (String image : images) {
										// 生成图片
										Base64ForImg.GenerateImage(image,
												imagesBasePath
														+ questionImagesPath
														+ uuid + i);
										imgs.add(uuid + i);
										i++;
									}

									// 转json
									ObjectMapper mapper = new ObjectMapper();
									String imgString = mapper
											.writeValueAsString(imgs);
									question.setImgs(imgString);
									questionAdmireResponse.setImage(imgString);
								}
								question.setStatus(QuestionStatus.QU_STATUS_CHUSHI.getCode());
								question.setUuid(uuid);
								
								//User user2 = new User();
								if (StringUtils.isNotBlank(payType)) {
									questionAdmireResponse.setCode("3");
									questionAdmireResponse
											.setDes("请更新版本");
									return questionAdmireResponse;
									/*
									if (payType.equals("balance")
											|| payType.equals("VipBalance")) {
										questionAdmireResponse.setCode("3");
										questionAdmireResponse
												.setDes("请更新版本");
										return questionAdmireResponse;
										
										
										if (payType.equals("balance")) {
											Double balance = user.getBalance();
											if (balance >= money) {
												user2.setBalance(balance - money);
												user2.setPhoneNumber(phoneNum);
												question.setPayStatus(PayCommonUtil.PAYSUCCESS_STATUS);
												question.setPayType(PayTypeUtil.PAYTYPE_BALANCE);
												questionService.updateUserAndAddQuestion(user2, question);
												questionAdmireResponse.setCode("1");
												questionAdmireResponse
														.setDes("发布悬赏成功！");
												questionAdmireResponse
														.setCredateDate(date);
												questionAdmireResponse.setTime(date.getTime());
												return questionAdmireResponse;

											} else {
												// 余额不足
												questionAdmireResponse.setCode("4");
												questionAdmireResponse
														.setDes("余额不足");
												return questionAdmireResponse;
											}

										} else {
											if(payType.equals("VipBalance")){
												questionAdmireResponse.setCode("3");
												questionAdmireResponse
														.setDes("此功能只支持最新版本");
												return questionAdmireResponse;
											}
											int i = payVipBanlanceService.updateUserAndCompany(user,money,question);
											if(i==1||i==2){
												questionAdmireResponse.setCode("1");
												questionAdmireResponse
														.setDes("发布悬赏成功！");
												questionAdmireResponse
														.setCredateDate(date);
												questionAdmireResponse.setTime(date.getTime());
												return questionAdmireResponse;
												
											}else if(i==3){
												//数据错误
												questionAdmireResponse.setCode("3");
												questionAdmireResponse.setDes("数据格式错误");
												return questionAdmireResponse;
											}else if(i==4){
												//余额不足
												questionAdmireResponse.setCode("4");
												questionAdmireResponse
														.setDes("会员卡余额不足");
												return questionAdmireResponse;
											}else if(i==0){
												//系统繁忙
												questionAdmireResponse.setCode("0");
												questionAdmireResponse.setDes("系统繁忙");
												return questionAdmireResponse;
											}
											
								}

									} else if (payType.equals("weixin")) {
										
									
										
										WxAppPayReq wxAppPayReq = new WxAppPayReq();
										wxAppPayReq.setPhone(phoneNum);
										double price = money;
										wxAppPayReq.setUnitPrice(price);
										wxAppPayReq.setProductName("悬赏问题");
										wxAppPayReq.setProductType(Const.XS);
										if (orderNo != null) {
											WxOrder wxOrder = wxOrderService
													.getWxOrderById(orderNo);
											if (wxOrder != null) {
												String productId = wxOrder
														.getProductId();
												wxAppPayReq.setProductId(productId);
												wxAppPayReq.setOrderNo(orderNo);
												WxAppPayRes appPay = (WxAppPayRes) weiXinPayService
														.appPay(wxAppPayReq,
																request);

												BeanUtils.copyProperties(
														wxAppResponse, appPay);
												wxAppResponse.setCredateDate(date);
												return wxAppResponse;

											}
										} else {
											
											if(source==1){
												WxJsPayReq req=new WxJsPayReq();
												req.setCode(code);
												req.setPhone(phoneNum);
												
												req.setUnitPrice((double)money);
												req.setProductName("悬赏问题");
												req.setProductType(Const.XS);
												req.setProductId(uuid);
												WxjsPayRes jssdPayRes=(WxjsPayRes)weiXinPayService.jSSDKPayInfo(req, request);
												questionService.addQuestion(question);
												return jssdPayRes;
											}else {
												
												wxAppPayReq.setProductId(uuid);
												WxAppPayRes appPay = (WxAppPayRes) weiXinPayService
														.appPay(wxAppPayReq, request);
												
												question.setPayStatus(PayCommonUtil.PAYPENDING_STATUS);
												question.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
												questionService.addQuestion(question);
												BeanUtils.copyProperties(wxAppResponse,
														appPay);
												wxAppResponse.setCredateDate(date);
												wxAppResponse.setTime(date.getTime());
												return wxAppResponse;
											}

										}

									} else if(payType.equals("personal")){
										
											questionAdmireResponse.setCode("3");
											questionAdmireResponse.setDes("请更新版本");
											return questionAdmireResponse;
										
										Double vipBalance = user.getVipBalance();
										
										if (vipBalance >= money) {
											user2.setVipBalance(vipBalance-money);
											user2.setPhoneNumber(phoneNum);
											question.setPayStatus(PayCommonUtil.PAYSUCCESS_STATUS);
											question.setPayType(PayTypeUtil.PAYTYPE_VIPBALANCE);
											questionService.updateUserAndAddQuestion(user2, question);
											questionAdmireResponse.setCode("1");
											questionAdmireResponse
													.setDes("发布悬赏成功！");
											questionAdmireResponse
													.setCredateDate(date);
											questionAdmireResponse.setTime(date.getTime());
											return questionAdmireResponse;

										} else {
											// 余额不足
											questionAdmireResponse.setCode("4");
											questionAdmireResponse
													.setDes("个人会员卡余额不足");
											return questionAdmireResponse;
										}

									
									}else if(payType.equals("business")){
										questionAdmireResponse.setCode("3");
										questionAdmireResponse.setDes("请更新版本");
										return questionAdmireResponse;
										HashMap<String,String> map = questionService.updateCompanyAndQuestion(user, money, question);
										return map;
									}else {
										// 数据格式错误
										questionAdmireResponse.setCode("4");
										questionAdmireResponse.setDes("请选择支付方式");
									}
								*/}
							
								question.setPayStatus(PayCommonUtil.PAYSUCCESS_STATUS);
								question.setPayType(PayTypeUtil.PAYTYPE_FREE);
								questionService.addQuestion(question);
								IntegralService.integral(phoneNum, "question", 5);
								questionAdmireResponse.setCode(BaseRes.SUCCESS_CODE);
								questionAdmireResponse
										.setDes(BaseRes.SUCCESS_DES);
								questionAdmireResponse
										.setCredateDate(date);
								questionAdmireResponse.setTime(date.getTime());
							
						} else {
							// 数据格式错误
							questionAdmireResponse.setCode("3");
							questionAdmireResponse.setDes("数据格式错误");
						}

					} else {
						// 数据格式错误
						questionAdmireResponse.setCode("3");
						questionAdmireResponse.setDes("数据格式错误");
					}

				} else {
					questionAdmireResponse.setCode("2");
					questionAdmireResponse.setDes("请重新登陆");
					// 未登录
				}

			//} else {
				//questionAdmireResponse.setCode("2");
				//questionAdmireResponse.setDes("请重新登陆");
			//}
			logger.info("返回：" + mapper.writeValueAsString(questionAdmireResponse));

		} catch (Exception e) {
			e.printStackTrace();
			questionAdmireResponse.setCode("0");
			questionAdmireResponse.setDes("系统繁忙");
		}

		return questionAdmireResponse;
	}

	// 偷偷看列表接口
	@RequestMapping(value = "/secretly", method = RequestMethod.POST)
	@ResponseBody
	public Object secretlyQuestion(HttpServletRequest request,
			@RequestBody QuestionRequest questionRequest) {
		SecretlyQuestionResponse secretlyQuestionResponse = new SecretlyQuestionResponse();
		try {
			logger.info("接收：" + mapper.writeValueAsString(questionRequest));

			CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
			
				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {
						QuestionExample questionExample = new QuestionExample();
						int sinceId = questionRequest.getSinceId();
						int maxId = questionRequest.getMaxId();
						if (sinceId <= 0) {
							sinceId = 1;
						}
						if (maxId <= 0 || maxId < sinceId) {
							maxId = sinceId;
						}
						questionExample.setPageIndex(sinceId - 1);
						questionExample.setPageSize(maxId - sinceId + 1);
						questionExample.setOrderByClause("date desc");
						Criteria criteria = questionExample.createCriteria();
						criteria.andStatusEqualTo(3);
						PagePhone pagePhone = new PagePhone();

						pagePhone.setPageIndex(sinceId - 1);
						pagePhone.setPageSize(maxId - sinceId + 1);
						pagePhone.setPhoneNum(phoneNum);
						List<QuestionUserEx> questionUserExs = questionExService
								.getPageQuesiotnUser(pagePhone);
						if(questionUserExs!=null){
							
							for (QuestionUserEx question : questionUserExs) {
								QuestionUserExample questionUserExample2 = new QuestionUserExample();
								QuestionUserKey questionUserKey2 = new QuestionUserKey();
								questionUserKey2.setPhoneNumber(phoneNum);
								questionUserKey2
								.setQuestionUuid(question.getUuid());
								QuestionUserKey questionUserKey = questionUserService
										.getQuestionUserKeys(questionUserKey2);
								if (question.getPhoneNumber().equals(phoneNum)
										|| questionUserKey != null) {
									question.setStatus(1);// 自己公开的和查看过的
									
								} else {
									question.setStatus(2);// 没有偷看过的
								}
								String counselorDuty = question.getCounselorDuty();
								StringBuilder stringBuilder=new StringBuilder();
								if(counselorDuty!=null&&!counselorDuty.equals("")){
									String[] dutys = counselorDuty.split(",");
									for (String id : dutys) {
										if(id!=null&&!id.equals("")){
											Duty duty = counselorDutyService.getDutyById(id);
											if(duty!=null){
												
												stringBuilder.append(duty.getDutyName()+" ");
											}
										}
									}
									int i = stringBuilder.lastIndexOf(" ");
									stringBuilder.delete(i, i+1);
									question.setCounselorDuty(stringBuilder.toString());
								}
								
								List<Answer> answers = answerUserService.getAnswer(
										question.getUuid(), 2);
								if (null != answers&&answers.size()>0) {
									Answer answer = answers.get(0);
									
									question.setApproveNum(answer.getApproveNum());// 赞成数目
								}
								com.jieshuibao.model.db.QuestionUserExample.Criteria criteria3 = questionUserExample2
										.createCriteria();
								criteria3
								.andQuestionUuidEqualTo(question.getUuid());
								int lookNum = questionUserService
										.countUser(questionUserExample2);
								question.setLookNum(lookNum);// 看过的数量
							}
						}
						secretlyQuestionResponse.setCode("1");
						secretlyQuestionResponse.setSinceId(sinceId);
						secretlyQuestionResponse.setMaxId(sinceId
								+ questionUserExs.size() - 1);
						secretlyQuestionResponse
								.setRows(questionUserExs.size());
						secretlyQuestionResponse
								.setQuestionImagesUrl(questionImagesUrl);
						// System.out.println(questionImagesUrl);
						secretlyQuestionResponse.setQuestions(questionUserExs);
					} else {
						// 重新登录
						secretlyQuestionResponse.setCode("2");
						secretlyQuestionResponse.setDes("请重新登陆");
					}
				} else {
					// 重新登录
					secretlyQuestionResponse.setCode("2");
					secretlyQuestionResponse.setDes("请重新登陆");
				}

			logger.info("返回："
					+ mapper.writeValueAsString(secretlyQuestionResponse));

		} catch (Exception e) {
			e.printStackTrace();
			secretlyQuestionResponse.setCode("0");
			secretlyQuestionResponse.setDes("系统繁忙请稍后再试！");

		}

		return secretlyQuestionResponse;
	}
			// 分享偷偷看列表接口
	@RequestMapping(value = "/secretlyShare", method = RequestMethod.POST)
	@ResponseBody
	public Object secretlyQuestionTwo(HttpServletRequest request,
			@RequestBody QuestionRequest questionRequest) {
		SecretlyQuestionResponse secretlyQuestionResponse = new SecretlyQuestionResponse();
		try {
			logger.info("接收：" + mapper.writeValueAsString(questionRequest));

						int sinceId = questionRequest.getSinceId();
						int maxId = questionRequest.getMaxId();

						if (sinceId <= 0) {
							sinceId = 1;
						}
						if (maxId <= 0 || maxId < sinceId) {
							maxId = sinceId;
						}
						
						PagePhone pagePhone = new PagePhone();

						pagePhone.setPageIndex(sinceId - 1);
						pagePhone.setPageSize(maxId - sinceId + 1);
						
						List<QuestionUserEx> questionUserExs = questionExService
								.getPageQuesiotnUserShare(pagePhone);
						
						if(questionUserExs!=null){
							
							for (QuestionUserEx question : questionUserExs) {
								QuestionUserExample questionUserExample2 = new QuestionUserExample();
								String counselorDuty = question.getCounselorDuty();
								StringBuilder stringBuilder=new StringBuilder();
								if(counselorDuty!=null&&!counselorDuty.equals("")){
									String[] dutys = counselorDuty.split(",");
									for (String id : dutys) {
										if(id!=null&&!id.equals("")){
											Duty duty = counselorDutyService.getDutyById(id);
											if(duty!=null){
												
												stringBuilder.append(duty.getDutyName()+" ");
											}
										}
									}
									int i = stringBuilder.lastIndexOf(" ");
									stringBuilder.delete(i, i+1);
									question.setCounselorDuty(stringBuilder.toString());
								}
								
								List<Answer> answers = answerUserService.getAnswer(
										question.getUuid(), 2);
								if (null != answers&&answers.size()>0) {
									Answer answer = answers.get(0);
									
									question.setApproveNum(answer.getApproveNum());// 赞成数目
								}
								com.jieshuibao.model.db.QuestionUserExample.Criteria criteria3 = questionUserExample2
										.createCriteria();
								criteria3.andQuestionUuidEqualTo(question.getUuid());
								int lookNum = questionUserService
										.countUser(questionUserExample2);
								question.setLookNum(lookNum);// 看过的数量
							}
						}
						secretlyQuestionResponse.setCode("1");
						secretlyQuestionResponse.setSinceId(sinceId);
						secretlyQuestionResponse.setMaxId(sinceId
								+ questionUserExs.size() - 1);
						secretlyQuestionResponse
								.setRows(questionUserExs.size());
						secretlyQuestionResponse
								.setQuestionImagesUrl(questionImagesUrl);
						secretlyQuestionResponse.setQuestions(questionUserExs);
					

			logger.info("返回："
					+ mapper.writeValueAsString(secretlyQuestionResponse));

		} catch (Exception e) {
			e.printStackTrace();
			secretlyQuestionResponse.setCode("0");
			secretlyQuestionResponse.setDes("系统繁忙请稍后再试！");

		}

		return secretlyQuestionResponse;
	}

	/**
	 * 快速问发布接口
	 * @param request
	 * @param questionAdmireRequest
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value="/releaseQuestion",method=RequestMethod.POST)
	@ResponseBody
	public Object releaseQuestion(HttpServletRequest request,@RequestBody QuestionAdmireRequest questionAdmireRequest) throws IOException {
		QuestionAdmireResponse questionAdmireResponse = new QuestionAdmireResponse();
		WxAppResponse wxAppResponse = new WxAppResponse();
		try {
			logger.debug("接收：" + mapper.writeValueAsString(questionAdmireRequest));
			CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
			//用户主键
			String phoneNum = cookieUser.getPhoneNumber();
			//用户是否完善信息，未完善个人信息
			boolean completeUser = userService.isCompleteUser(phoneNum);
			if (!completeUser) {
				questionAdmireResponse.setCode(BaseRes.ERRORPARAM_CODE);
				questionAdmireResponse.setDes("请完善用户信息");
				return questionAdmireResponse;
			}
			//是否存在未采纳的提问，存在则不允许发布提问
			boolean adopQuestion = questionService.isAdopQuestion(phoneNum);
			if (adopQuestion) {
				questionAdmireResponse.setCode(BaseRes.ERRORPARAM_CODE);
				questionAdmireResponse.setDes("您还有问题尚未采纳，请采纳后再进行发布！");
				return questionAdmireResponse;
			}
			//提问
			Question question = new Question();
			String content = questionAdmireRequest.getContent();//内容
			
		
			int money = questionAdmireRequest.getMoney();//快速问金额
			String trade = questionAdmireRequest.getTrade();//行业
			String isAnon = questionAdmireRequest.getIsAnon();//是否隐藏
			if(StringUtils.isBlank(content) || StringUtils.isBlank(isAnon)){
				questionAdmireResponse.setCode("3");
				questionAdmireResponse.setDes("数据格式错误");
				return questionAdmireResponse;
			}
			
			//当行业为空时，则保存用户信息里面的行业，都无数据时，为空
			if(StringUtils.isBlank(trade)){
				question.setTrade(cookieUser.getTrade());
			}else{
				question.setTrade(trade);
			}
			if(money != minMoney){
				questionAdmireResponse.setCode("3");
				questionAdmireResponse.setDes("金额错误");
				return questionAdmireResponse;
			}
			question.setMoney(minMoney);//快速问价格
			question.setPhoneNum(phoneNum);//用户主键
			if (isAnon.equals("0")) {
				question.setIsAnon("0");
			}else{
				question.setIsAnon("1");
			}
			//判断内容是否存在非法字符
			boolean containtSensitiveWord = SensitivewordFilterService.isContaintSensitiveWord(content, 2);
			if (containtSensitiveWord) {
				questionAdmireResponse.setCode("3");
				questionAdmireResponse.setDes("包含非法字符请检查后再发布！");
				return questionAdmireResponse;
			}
			//替换敏感字符
			 content = SensitivewordFilterService.replaceSensitiveWord(content, 2, "*");
			
			//内容
			question.setContent(content);
			//直辖市或者省份
			String province = cookieUser.getProvince();
			//用户的地址
			//String address = cookieUser.getAddress();
			//省份/直辖市
			question.setArea(province);
			//获取请求主机IP地址
			String ipAddress = NetworkUtil.getIpAddress(request);
			//发问题的ip
			question.setQuIp(ipAddress);
			//提问主键
			String uuid = UUIDGenerator.getUUID();
			question.setUuid(uuid);
			//获取图片信息
			List<String> images = questionAdmireRequest.getImages();
			// 图片处理
			if (images != null && images.size() > 0) {
				int i = 1;
				List<String> imgs = new ArrayList<String>();
				for (String image : images) {
					//生成图片
					Base64ForImg.GenerateImage(image,imagesBasePath + questionImagesPath + uuid + i);
					imgs.add(uuid + i);
					i++;
				}
				//转JSON
				ObjectMapper mapper = new ObjectMapper();
				String imgString = mapper.writeValueAsString(imgs);
				question.setImgs(imgString);
				questionAdmireResponse.setImage(imgString);
			}
		
			//完善提问
			question = questionExService.perfectQuestion(question);
			//获取支付方式
			String payType = questionAdmireRequest.getPayType();
			
			if (StringUtils.isBlank(payType)) {
				questionAdmireResponse.setCode("3");
				questionAdmireResponse.setDes("请更新版本");
				return questionAdmireResponse;
			}
			User user = userService.getUserByPhoneNumber(phoneNum);

			User user2 = new User();
			if(payType.equals("balance") || payType.equals("VipBalance") || payType.equals("QACardBalance")){
				Double balance = 0.00;
				//获取余额
				if(payType.equals("balance")){
					balance = cookieUser.getBalance();//钱包余额
					if(balance == null || balance <= 0){
						// 余额不足
						questionAdmireResponse.setCode("4");
						questionAdmireResponse.setDes("余额不足");
						return questionAdmireResponse;
					}
					user2.setBalance(balance-money);
					question.setPayType(PayTypeUtil.PAYTYPE_BALANCE);//钱包余额支付 
				}else if(payType.equals("VipBalance")){//财税顾问卡支付
					balance = user.getVipBalance();
					if(balance == null || balance <= 0){
						// 余额不足
						questionAdmireResponse.setCode("4");
						questionAdmireResponse.setDes("余额不足");
						return questionAdmireResponse;
					}
					user2.setVipBalance(balance-money);
					question.setPayType(PayTypeUtil.PAYTYPE_VIPBALANCE);//财税顾问卡余额
				}else if(payType.equals("QACardBalance")){
					balance = user.getQACardBlance();//财税问答卡余额
					if(balance == null || balance <= 0){
						// 余额不足
						questionAdmireResponse.setCode("4");
						questionAdmireResponse.setDes("余额不足");
						return questionAdmireResponse;
					}
					user2.setQACardBlance(balance-money);
					question.setPayType(PayTypeUtil.PAYTYPE_QACARDBALANCE);//财税问答卡支付
				}
				//判断是否余额不足
				if (balance >= money) {
					user2.setPhoneNumber(phoneNum);
					question.setPayStatus(PayCommonUtil.PAYSUCCESS_STATUS);
					questionService.updateUserAndAddQuestion(user2, question);
					//用户增加积分
					IntegralService.integral(phoneNum, "question", 5);
					questionAdmireResponse.setCode(BaseRes.SUCCESS_CODE);
					questionAdmireResponse.setDes("发布成功");
					questionAdmireResponse.setCredateDate(new Date());
					questionAdmireResponse.setTime(questionAdmireResponse.getCredateDate().getTime());
					return questionAdmireResponse;
				}else{
					// 余额不足
					questionAdmireResponse.setCode("4");
					questionAdmireResponse.setDes("余额不足");
					return questionAdmireResponse;
				}
			}else if(payType.equals("weixin")) {
				question.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);//财税问答卡支付
				questionService.addQuestion(question);
				
				int source = questionAdmireRequest.getSource();
				if (source==1) {
					String code = questionAdmireRequest.getCode();
					WxJsPayReq wxreq = new WxJsPayReq();
					wxreq.setCode(code);
					wxreq.setPhone(phoneNum);
					wxreq.setUnitPrice((double)money);
					wxreq.setProductName("快速问");
					wxreq.setProductType(Const.XS);
					wxreq.setProductId(uuid);
					WxjsPayRes jssdPayRes = (WxjsPayRes) weiXinPayService
							.jSSDKPayInfo(wxreq, request);
					return jssdPayRes;
					
				}
				
				WxAppPayReq wxAppPayReq = new WxAppPayReq();
				wxAppPayReq.setPhone(phoneNum);
				wxAppPayReq.setUnitPrice((double)money);
				wxAppPayReq.setProductName("快速问");
				wxAppPayReq.setProductType(Const.XS);
				wxAppPayReq.setProductId(question.getUuid());
				WxAppPayRes appPay = (WxAppPayRes) weiXinPayService.appPay(wxAppPayReq, request);
				BeanUtils.copyProperties(wxAppResponse,appPay);
				wxAppResponse.setCredateDate(new Date());
				wxAppResponse.setTime(wxAppResponse.getCredateDate().getTime());
				return wxAppResponse;
			}else{
				questionAdmireResponse.setCode("3");
				questionAdmireResponse.setDes("请更新版本");
				return questionAdmireResponse;
			}
		} catch (Exception e) {
			e.printStackTrace();
			questionAdmireResponse.setCode(BaseRes.FAIL_CODE);
			questionAdmireResponse.setDes(BaseRes.FAIL_DES);
		}
		return questionAdmireResponse;
	}
}
